import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Modal, Button } from 'antd';
import { connect } from 'umi';
import isEmail from 'validator/lib/isEmail';
import isMobilePhone from 'validator/lib/isMobilePhone';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

const names = {
  name1: 'username',
  name2: 'name',
  name3: 'roleVoList',
  name4: 'email',
  name5: 'telNum',
  name6: 'password',
  name7: 'confirmPassword',
};

var UserAdd = props => {
  const [form] = Form.useForm();
  const myRef = React.useRef();
  const {
    addVisibleModalType,
    addVisibleModalUserId,
    allRoleList,
  } = props.UserList;

  //根据id查询用户信息
  var getUserInfoById = async () => {
    var rs = await props.dispatch({
      type: 'UserList/getUserInfoById',
      payload: { id: addVisibleModalUserId },
    });
    if (rs.success) {
      var result = [];
      result = rs.data.roleVoList?.map((item, i) => {
        return (result[i] = item.id);
      });

      var data = {
        username: rs.data.username,
        name: rs.data.name,
        telNum: rs.data.telNum,
        email: rs.data.email,
        password: '123456789123',
        roleVoList: result,
      };
      console.log('data',data);
      form.setFieldsValue(data);
    }
  };

  useEffect(() => {
    if (props.init) props.init(form);
    // 不是add情况查询用户信息
    if (addVisibleModalType != 'add') {
      getUserInfoById();
    }
  }, []);

  var disabled = true;
  if (addVisibleModalType == 'add') disabled = false;
  if (addVisibleModalType == 'update') disabled = false;

  return (
    <div>
  
        <Form {...formItemLayout} form={form}>
          <Form.Item
            name={names.name1}
            label="用户名"
            rules={[
              { required: true, message: '用户名必须输入' },
              {
                pattern: /^[a-zA-Z0-9]{4,16}$/,
                message: '用户名必须4到16位（字母，数字）',
              },
            ]}
          >
            <Input placeholder="用户名" disabled={disabled} />
          </Form.Item>
          <Form.Item
            name={names.name2}
            label="姓名"
            rules={[
              { required: true, message: '姓名必须输入' },
              {
                pattern: /(^(?:[\u4e00-\u9fa5·]{2,255})$)|(^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]$)/,
                message: '姓名必须是中文或英文（最少2个字符）',
              },
            ]}
          >
            <Input placeholder="姓名" disabled={disabled} />
          </Form.Item>
          <Form.Item
            name={names.name3}
            label="角色分类"
            rules={[{ required: true, message: '角色必须选择' }]}
          >
            <Select
              placeholder="请选择角色"
              disabled={disabled}
              mode="multiple"
              allowClear
            >
              {allRoleList.map(item => {
                return (
                  <Select.Option key={item.id} value={item.id}>
                    {item.roleName}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            name={names.name4}
            label={<span className={'must'}>邮箱</span>}
            rules={[
              {
                validator: async (rule, value) => {
                  if (!value) {
                    return Promise.reject('邮箱必须输入');
                  }
                  if (!isEmail(value)) {
                    return Promise.reject('邮箱格式不正确');
                  }
                },
              },
            ]}
          >
            <Input placeholder="邮箱" disabled={disabled} />
          </Form.Item>
          <Form.Item
            name={names.name5}
            label={<span className={'must'}>手机号</span>}
            rules={[
              {
                validator: async (rule, value) => {
                  if (!value) {
                    return Promise.reject('手机号必须输入');
                  }
                  if (!isMobilePhone(value, ['zh-CN'])) {
                    return Promise.reject('手机号不正确');
                  }
                },
              },
            ]}
          >
            <Input placeholder="手机号" disabled={disabled} />
          </Form.Item>

          <>
            {addVisibleModalType != 'view' && (
              <Form.Item
                name={names.name6}
                label="密码"
                rules={[{ required: true, message: '密码必须输入' }]}
              >
                <Input
                  ref={myRef}
                  type="password"
                  placeholder="密码"
                  disabled={disabled}
                  onChange={e => {
                    props.dispatch({
                      type: 'UserList/setState',
                      payload: { password: e.target.value },
                    });
                  }}
                />
              </Form.Item>
            )}

            {addVisibleModalType == 'add' && (
              <Form.Item
                name={names.name7}
                label={<span className={'must'}>确认密码</span>}
                rules={[
                  {
                    validator: async (rule, value) => {
                      if (!value) {
                        return Promise.reject('密码必须输入');
                      }
                      var password = form.getFieldValue('password');
                      if (password && password != value) {
                        return Promise.reject('两次输入密码不一致');
                      }
                    },
                  },
                ]}
              >
                <Input
                  type="password"
                  placeholder="确认密码"
                  disabled={disabled}
                />
              </Form.Item>
            )}
          </>
        </Form>
      
    </div>
  );
};

export default connect(({ UserList }) => ({ UserList }))(UserAdd);
